<template>
  <div class="collaboration-panel">
    <!-- 在线用户列表 -->
    <div class="online-users-section">
      <h3 class="section-title">
        <span class="icon">👥</span>
        在线用户 ({{ onlineUsers.length }})
      </h3>
      <div class="users-list">
        <div 
          v-for="user in onlineUsers" 
          :key="user.id"
          class="user-item"
          :class="{ 'current-user': user.id === currentUserId }"
        >
          <div class="user-avatar">
            {{ user.userName?.charAt(0)?.toUpperCase() || '?' }}
          </div>
          <div class="user-info">
            <div class="user-name">
              {{ user.userName }}
              <span v-if="user.id === currentUserId" class="current-label">(我)</span>
            </div>
            <div class="user-status">
              <span class="status-dot online"></span>
              正在编辑
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 连接状态
    <div class="connection-status">
      <div class="status-item" :class="connectionStatus.class">
        <span class="status-dot" :class="connectionStatus.class"></span>
        {{ connectionStatus.text }}
      </div>

    </div> -->

    <!-- 实时消息 -->
    <div class="messages-section">
      <h3 class="section-title">
        <span class="icon">💬</span>
        协作消息
      </h3>
      <div class="messages-list" ref="messagesContainer">
        <div 
          v-for="(message, index) in recentMessages" 
          :key="index"
          class="message-item"
          :class="message.type"
        >
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          <div class="message-content">
            <span v-if="message.user" class="message-user">{{ message.user.userName }}:</span>
            {{ message.text }}
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="actions-section">
      <button 
        @click="saveVersion" 
        class="action-btn primary"
        :disabled="!hasEditPermission || isSaving"
        title="保存当前版本"
      >
        <span class="icon">💾</span>
        {{ isSaving ? '保存中...' : '保存版本' }}
      </button>
      
      <button 
        @click="togglePanel" 
        class="action-btn secondary"
        title="收起面板"
      >
        <span class="icon">📋</span>
        {{ '收起' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useUserStore } from '@/stores/user';
import wsManager from '@/utils/websocket';
import { ElMessage } from 'element-plus';

// Props
const props = defineProps({
  documentId: {
    type: [String, Number],
    required: true
  },
  hasEditPermission: {
    type: Boolean,
    default: false
  }
});

// Emits
const emit = defineEmits(['save-version', 'toggle-panel']);

// Store
const userStore = useUserStore();

// 响应式数据
const onlineUsers = ref([]);
const recentMessages = ref([]);
const isConnected = ref(false);

const isSaving = ref(false);
const isCollapsed = ref(false);
const messagesContainer = ref(null);

// 计算属性
const currentUserId = computed(() => userStore.currentUser?.id);

const connectionStatus = computed(() => {
  if (isConnected.value) {
    return {
      text: '已连接',
      class: 'connected'
    };
  } else {
    return {
      text: '连接中...',
      class: 'connecting'
    };
  }
});

// 方法
const addMessage = (text, type = 'info', user = null) => {
  const message = {
    text,
    type,
    user,
    timestamp: new Date()
  };
  
  recentMessages.value.push(message);
  
  // 限制消息数量
  if (recentMessages.value.length > 50) {
    recentMessages.value.shift();
  }
  
  // 滚动到底部
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

const addUserToOnlineList = (user) => {
  if (!onlineUsers.value.find(u => u.id === user.id)) {
    onlineUsers.value.push(user);
  }
};

const removeUserFromOnlineList = (userId) => {
  const index = onlineUsers.value.findIndex(u => u.id === userId);
  if (index > -1) {
    onlineUsers.value.splice(index, 1);
  }
};

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

const saveVersion = () => {
  if (!props.hasEditPermission) {
    ElMessage.warning('您没有编辑权限');
    return;
  }
  
  isSaving.value = true;
  emit('save-version');
  
  // 通过WebSocket发送保存版本请求
  wsManager.sendSaveVersion();
  
  // 模拟保存完成（实际应该等待服务器响应）
  setTimeout(() => {
    isSaving.value = false;
  }, 2000);
};

const togglePanel = () => {
  isCollapsed.value = !isCollapsed.value;
  emit('toggle-panel', isCollapsed.value);
};

// WebSocket事件处理
const setupWebSocketHandlers = () => {
  // 连接成功
  wsManager.on('connected', () => {
    isConnected.value = true;
    addMessage('已连接到协作服务器', 'success');
    
    // 连接成功后添加当前用户到在线列表
    if (userStore.currentUser) {
      addUserToOnlineList(userStore.currentUser);
    }
  });
  
  // WebSocket连接断开
  wsManager.on('disconnected', () => {
    isConnected.value = false;
    addMessage('连接已断开', 'warning');
    
    // 断开连接时清空在线用户列表
    onlineUsers.value = [];
  });
  
  // 接收到信息消息
  wsManager.on('info', (data) => {
    addMessage(data.message, 'info', data.user);
    
    // 如果是用户加入/离开消息，更新在线用户列表
    if (data.user && data.message.includes('加入协作编辑')) {
      addUserToOnlineList(data.user);
    } else if (data.user && data.message.includes('离开协作编辑')) {
      removeUserFromOnlineList(data.user.id);
    }
  });
  
  // 接收到文档内容
  wsManager.on('documentContent', (data) => {
    addMessage('文档已同步', 'success');
  });
  
  // 编辑操作
  wsManager.on('editAction', (data) => {
    if (data.user && data.user.id !== currentUserId.value) {
      const operationText = {
        'INSERT': '插入了内容',
        'DELETE': '删除了内容',
        'REPLACE': '替换了内容'
      }[data.operation] || '进行了编辑';
      
      addMessage(`${operationText}`, 'edit', data.user);
    }
  });
  
  // 版本保存
  wsManager.on('versionSaved', (data) => {
    addMessage(data.message, 'success', data.user);
    isSaving.value = false;
  });
  
  // 错误消息
  wsManager.on('error', (data) => {
    addMessage(data.message, 'error', data.user);
    isSaving.value = false;
  });
};

// 生命周期
onMounted(() => {
  setupWebSocketHandlers();
  addMessage('协作面板已启动', 'info');
});

onBeforeUnmount(() => {
  // 清理WebSocket事件监听器
  wsManager.off('connected');
  wsManager.off('disconnected');
  wsManager.off('info');
  wsManager.off('documentContent');
  wsManager.off('editAction');
  wsManager.off('versionSaved');
  wsManager.off('error');
});
</script>

<style scoped>
.collaboration-panel {
  position: fixed;
  top: 80px;
  right: 20px;
  width: 300px;
  height: calc(100vh - 120px);
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  font-size: 14px;
  z-index: 1000;
  overflow: hidden;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 12px 0;
  padding: 16px 16px 0 16px;
}

.icon {
  font-size: 18px;
}

/* 在线用户部分 */
.online-users-section {
  border-bottom: 1px solid #f3f4f6;
  padding-bottom: 16px;
}

.users-list {
  padding: 0 16px;
  max-height: 200px;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f9fafb;
}

.user-item:last-child {
  border-bottom: none;
}

.user-item.current-user {
  background-color: #f0f9ff;
  border-radius: 6px;
  padding: 8px;
  margin: 4px 0;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 14px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #374151;
  margin-bottom: 2px;
}

.current-label {
  color: #3b82f6;
  font-size: 12px;
}

.user-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6b7280;
}

/* 连接状态 */
.connection-status {
  padding: 16px;
  border-bottom: 1px solid #f3f4f6;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.status-dot.connected {
  background-color: #10b981;
}

.status-dot.connecting {
  background-color: #f59e0b;
  animation: pulse 2s infinite;
}

.status-dot.online {
  background-color: #10b981;
}



/* 消息部分 */
.messages-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.messages-list {
  flex: 1;
  padding: 0 16px 16px 16px;
  overflow-y: auto;
  max-height: 300px;
}

.message-item {
  margin-bottom: 12px;
  padding: 8px;
  border-radius: 6px;
  background-color: #f9fafb;
}

.message-item.success {
  background-color: #ecfdf5;
  border-left: 3px solid #10b981;
}

.message-item.warning {
  background-color: #fffbeb;
  border-left: 3px solid #f59e0b;
}

.message-item.error {
  background-color: #fef2f2;
  border-left: 3px solid #ef4444;
}

.message-item.edit {
  background-color: #eff6ff;
  border-left: 3px solid #3b82f6;
}

.message-time {
  font-size: 11px;
  color: #9ca3af;
  margin-bottom: 4px;
}

.message-content {
  font-size: 13px;
  color: #374151;
  line-height: 1.4;
}

.message-user {
  font-weight: 500;
  color: #4f46e5;
}

/* 操作按钮 */
.actions-section {
  padding: 16px;
  border-top: 1px solid #f3f4f6;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.primary {
  background-color: #4f46e5;
  color: white;
}

.action-btn.primary:hover:not(:disabled) {
  background-color: #4338ca;
}

.action-btn.primary:disabled {
  background-color: #d1d5db;
  color: #9ca3af;
  cursor: not-allowed;
}

.action-btn.secondary {
  background-color: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.action-btn.secondary:hover {
  background-color: #e5e7eb;
}

/* 动画 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 滚动条样式 */
.users-list::-webkit-scrollbar,
.messages-list::-webkit-scrollbar {
  width: 4px;
}

.users-list::-webkit-scrollbar-track,
.messages-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.users-list::-webkit-scrollbar-thumb,
.messages-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.users-list::-webkit-scrollbar-thumb:hover,
.messages-list::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
</style>